﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Runtime.Serialization;
using RestEntities;
using System.IO;
using System.Windows.Interop;

namespace WpfAppWcfRestConsumer
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private Person CurrentPerson;
		private Comment CurrentComment;

		public MainWindow()
		{
			InitializeComponent();
			CurrentPerson = null;
			CurrentComment = null;
			this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
			this.Closing += (s, e) =>
			{
				HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
				if (hwndSource != null)
				{
					hwndSource.RemoveHook(hwndSourceHook);
				}
			};
		}

		protected override void OnSourceInitialized(EventArgs e)
		{
			base.OnSourceInitialized(e);

			HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
			if (hwndSource != null)
			{
				hwndSource.AddHook(hwndSourceHook);
			}
		}

		IntPtr hwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			switch (msg)
			{
				case Win32.WM_DEVICECHANGE:
					{
						switch ((int)wParam)
						{
							case Win32.DBT_DEVICEARRIVAL:
								int devType = System.Runtime.InteropServices.Marshal.ReadInt32(lParam, sizeof(int));
								if (devType == Win32.DBT_DEVTYP_VOLUME)
								{
									SystemHelperLibrary.DeviceExt.Hardware.Native.DEV_BROADCAST_VOLUME vol;
									vol = (SystemHelperLibrary.DeviceExt.Hardware.Native.DEV_BROADCAST_VOLUME)System.Runtime.InteropServices.Marshal.PtrToStructure(lParam,
										typeof(SystemHelperLibrary.DeviceExt.Hardware.Native.DEV_BROADCAST_VOLUME));

									SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation(string.Format("Storage device inserted. Volume name {0}",
																										Win32.UnitName((int)vol.dbcv_unitmask)));

								}
								break;
							case Win32.DBT_DEVICEREMOVECOMPLETE:
								SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation("Device deleted completely");
								break;

							default:
								break;
						}
					}
					break;

				case Win32.WM_POWERBROADCAST:
					switch ((int)wParam)
					{
						case Win32.PBT_APMSUSPEND:
							SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation("Suspend");
							break;

						case Win32.PBT_APMRESUMESUSPEND:
							SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation("Resume/Suspend");
							break;

						case Win32.PBT_APMPOWERSTATUSCHANGE:
							SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation("Power status changed");
							break;

						case Win32.PBT_POWERSETTINGCHANGE:
							SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation("Power settings changed");
							break;

						default:
							break;
					}

					break;

				default:
					break;
			}

			return IntPtr.Zero;
		}

		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			SystemHelperLibrary.API.Win7.Win7Helper.ExtendGlass(this);
			//uint Gb2 = 0x80000000;
			//uint Gb4 = 0xFFFFFFFF;

			//if (SystemHelperLibrary.API.ApiHelper.IsLibraryExist("quickusb.dll"))
			//{
			//}

			////CopyFileTransacted, CreateDirectoryTransacted, CreateHardLinkTransacted, DeleteFileTransacted, MoveFileTransacted, RemoveDirectoryTransacted, and SetFileAttributesTransacted
			//SystemHelperLibrary.API.FilesExt.FileHelper.UseTransactionInFiles("c:\\1q.txt");

			//IntPtr hWndM=SystemHelperLibrary.API.ApiHelper.FindWindowApi("MainWindow");
			//SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.GetDesktops();
			//string[] captions=SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.GetDesktopWindowsCaptions();
			//var listDev=SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.ListDisplayDevices();

			//SystemHelperLibrary.API.AviFile.AviHelper.Initialize();
			//using (SystemHelperLibrary.API.AviFile.AviHelper avi = new SystemHelperLibrary.API.AviFile.AviHelper("D:\\Films\\Home Alone.avi"))
			//{
			//    int max = avi.GetMaxFrameCount();
			//    for (int i = 0; i < max; ++i)
			//    {
			//        System.Drawing.Bitmap bmp = avi.GetFrame(i);
			//        bmp.Save(string.Format("d:\\Films\\{0}.bmp", i));
			//        bmp.Dispose();
			//    }
			//}
			//SystemHelperLibrary.API.AviFile.AviHelper.Terminate();

			//var env = SystemHelperLibrary.API.SystemExt.SystemHelp.GetEnvironmentStringsApi();
			//var ms = SystemHelperLibrary.API.SystemExt.SystemHelp.GetMemoryStatusExApi();
			//SystemHelperLibrary.API.FilesExt.FileHelper.CreateFile();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.ConvertStringToOem("Helo31242~");
			//int tick = SystemHelperLibrary.API.SystemExt.SystemHelp.GetTickCountApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.IsCharAlphaApi('3');
			//SystemHelperLibrary.API.SystemExt.SystemHelp.OemToCharApi("Helo31242~");
			//SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.EnumCodePagesApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.EnumCodeLocalseApi();

			//uint id = SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.CreateTimerApi(IntPtr.Zero,
			//                                                                            1000);



			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetRealPath("F:\\");
			//SystemHelperLibrary.API.SystemExt.SystemHelp.RemoveUsb("F:\\");

			//string[] devices = SystemHelperLibrary.API.SystemExt.SystemHelp.QueryDosDeviceApi();

			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetEnvironmentVariableApi("windir");
			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetLogicalDrivesApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetSturtupInfoApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetSystemInfoApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetSystemTimeApi();
			//SystemHelperLibrary.API.SystemExt.SystemHelp.GetComputerNameApi();

			//if (SystemHelperLibrary.API.SystemExt.SystemHelp.Instance.DeleteTimerApi((PresentationSource.FromVisual(this) as HwndSource).Handle, id))
			//{
			//}

			//foreach (string dr in Environment.GetLogicalDrives())
			//{
			//    SystemHelperLibrary.API.SystemExt.SystemHelp.DRIVE_TYPE rez = SystemHelperLibrary.API.SystemExt.SystemHelp.GetDriveTypeApi(dr);
			//}

			//SystemHelperLibrary.API.Win7.Win7Helper.GetCurrentProcessExplicitAppUserModelIDApi();

			//bool wrRes = SystemHelperLibrary.API.Ini.IniHelper.WriteSection("c:\\1.ini", "DataPref2", "p3=v3\r\np4=v4\r\n");
			//wrRes = SystemHelperLibrary.API.Ini.IniHelper.WriteValue("c:\\1.ini", "DataPref2", "p3", "123456");
			//string val = SystemHelperLibrary.API.Ini.IniHelper.GetValue("c:\\1.ini", "DataPref2", "p3");
			//var strDt = SystemHelperLibrary.API.Ini.IniHelper.GetIniStruct("c:\\1.ini", "DataPref2", "p3");
			//SystemHelperLibrary.API.Ini.IniHelper.GetPrivateProfileSectionApi("PREFERENCES", @"C:\Games\Data.ini");
			//SystemHelperLibrary.API.Ini.IniHelper.GetSectionsNames(@"C:\Games\Data.ini");

			//if (Win32.GetSystemPowerStatusApi())
			//{
			//    Win32.GetBatteryFlag();
			//}
			//using (SystemHelperLibrary.API.WlanHelper help = new SystemHelperLibrary.API.WlanHelper())
			//{
			//    help.EnumerateNICs();
			//    if (help.AvaliableWiFiList.Count != 0)
			//    {
			//        var netw = help.EnumearteNetworks(help.AvaliableWiFiList[0]);
			//    }
			//    HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
			//    help.WlanEditProfileUI(hwndSource.Handle, "HomeDLINK");

			//    string ssid;
			//    int maxPeers;
			//    help.QueryConnectionSettings(out ssid, out maxPeers);
			//    help.QureryStatus();
			//    help.StartUsing();
			//    help.StopUsing();

			//    help.WlanScan();
			//    help.SetXmlProfile();

			//    help.GetProfileInfoList();

			//    string passKey;
			//    bool isPasePhrase;
			//    bool isPersistent;
			//    var dtat = help.QuerySecondaryKey(out passKey, out isPasePhrase, out isPersistent);

			//    if (help.AvailableNetworks.Count > 0)
			//        help.Connect(help.AvailableNetworks[0].SSID);

			//    help.Disconnect();

			//    string erorDescr = help.WlanReasonCodeTostringApi(524289);
			//    string profileXml = help.BuildProfileXml("Cawa", "112312");

			//    var d = profileXml;

			//    string profile = help.GetProfileXml("CAWA-ZU-56750");
			//    help.ForceStart();
			//    help.ForceStop();
			//    help.InitSettings();
			//}

			//bool isexist = SystemHelperLibrary.API.ApiHelper.IsLibraryExist("wlanapi.dll");
			//if (isexist)
			//{
			//}

			//int binCount = SystemHelperLibrary.API.ShellBin.GetCount();

			//SystemHelperLibrary.API.ShellBin.EmptyRecycleBin();

			//string dataStr = SystemHelperLibrary.API.ApiHelper.CharLowerApi("HELLO");

			//MessageBox.Show(SystemHelperLibrary.API.ApiHelper.GetUserNameApi());

			//SystemHelperLibrary.WpfExt.XamlHelper.WriteXaml("c:\\1.xaml", this.MainMenu);
			//string data = SystemHelperLibrary.WpfExt.XamlHelper.GetXamlDeclaration(this.MainMenu);

			//Menu menu = SystemHelperLibrary.WpfExt.XamlHelper.ReadXamlFromFile<Menu>(@"c:\1.xaml");

			//menu.Visibility = System.Windows.Visibility.Hidden;

			//var menu2 = SystemHelperLibrary.WpfExt.XamlHelper.ReadXamlFromContent<Menu>(data);

			//menu2.Width = 123;

			//SystemHelperLibrary.WpfExt.DialogsExt.Dialogs.ShowInformation(data);

			//SystemHelperLibrary.DeviceExt.Hardware.HardwareHelper hardware = new SystemHelperLibrary.DeviceExt.Hardware.HardwareHelper();
			//string[] HardData = hardware.GetAll();
			//if (HardData.Length > 2)
			//{
			//}

			//WindowInteropHelper interop = new WindowInteropHelper(Application.Current.MainWindow);
			//IntPtr ptr = interop.Handle;

			//string text = SystemHelperLibrary.API.ApiHelper.GetWindowTextApi(ptr.ToInt32());

			//text.Trim();

			//SystemHelperLibrary.WpfExt.WebCam.WebCamGrabber webCam = new SystemHelperLibrary.WpfExt.WebCam.WebCamGrabber(320, 240, 25, 0, ptr.ToInt32());

			//if (webCam.Devices.Count > 0)
			//{
			//}
		}


		private void miExit_Click(object sender, RoutedEventArgs e)
		{
			CurrentPerson = null;
			CurrentComment = null;
			Application.Current.Shutdown();
		}

		private void btnAdd_Click(object sender, RoutedEventArgs e)
		{
			Views.AddPersonWindow add = new Views.AddPersonWindow();
			add.Owner = this;
			if (add.ShowDialog() == true)
			{
				Person person = add.PersonInstance;
				DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
				// set up our request
				HttpWebRequest request =
				  (HttpWebRequest)HttpWebRequest.Create(@"http://localhost:2222/RestService/Admin/Person");
				request.Accept = "*/*";
				// we're going to post XML
				request.ContentType = "application/xml";
				request.Method = "POST";
				using (Stream stream = request.GetRequestStream())
				{
					// send data
					serializer.WriteObject(stream, person);
					stream.Flush();
				}

				// get the response
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				using (Stream stream = response.GetResponseStream())
				{
				}

			}
		}

		private void btnGetPersons_Click(object sender, RoutedEventArgs e)
		{
			lstComments.ItemsSource = null;
			lstPersons.ItemsSource = null;

			DataContractSerializer serializer = new DataContractSerializer(typeof(List<Person>));
			// set up our request
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"http://localhost:2222/RestService/Persons");
			request.Accept = "*/*";
			// we're going to post XML
			request.Method = "GET";

			List<Person> listPers = null;
			// get the response
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			using (Stream stream = response.GetResponseStream())
			{
				listPers = serializer.ReadObject(stream) as List<Person>;
			}

			lstPersons.ItemsSource = listPers;
		}

		private void lstPersons_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			CurrentPerson = lstPersons.SelectedItem as Person;

			if (CurrentPerson != null)
			{
				textId.Text = CurrentPerson.Id.ToString();

				DataContractSerializer serializer = new DataContractSerializer(typeof(List<Comment>));
				// set up our request
				HttpWebRequest request =
				  (HttpWebRequest)HttpWebRequest.Create(string.Format(@"http://localhost:2222/RestService/PersonCommentsById/{0}",
																		CurrentPerson.Id));
				request.Accept = "*/*";
				// we're going to post XML
				request.ContentType = "application/xml";
				request.Method = "GET";

				List<Comment> commentList = null;
				// get the response
				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				using (Stream stream = response.GetResponseStream())
				{
					commentList = serializer.ReadObject(stream) as List<Comment>;
				}

				lstComments.ItemsSource = commentList;
			}
		}

		private void btnAddComment_Click(object sender, RoutedEventArgs e)
		{
			if (CurrentPerson == null)
			{
				MessageBox.Show("First you must select person to add comment");
				return;
			}

			Comment com = null;
			Views.AddCommentWindow addComment = new Views.AddCommentWindow();

			if (addComment.ShowDialog() == true)
			{
				com = addComment.CommentData;

				DataContractSerializer ser = new DataContractSerializer(typeof(Comment));

				string url = string.Format(@"http://localhost:2222/RestService/Admin/{0}/Comment", CurrentPerson.Id.ToString());

				HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
				request.Accept = "*/*";
				request.ContentType = "application/xml";
				request.Method = "POST";
				using (Stream sr = request.GetRequestStream())
				{
					ser.WriteObject(sr, com);
					sr.Flush();
				}

				HttpWebResponse response = (HttpWebResponse)request.GetResponse();
				using (Stream stream = response.GetResponseStream())
				{

				}
			}
		}

		private void miDeleteComment_Click(object sender, RoutedEventArgs e)
		{
			string result = string.Empty;

			if (CurrentComment == null)
			{
				MessageBox.Show("First you must choose comment to delete");
				return;
			}

			string url = string.Format(@"http://localhost:2222/RestService/Admin/Comment/{0}", CurrentComment.CommentId);
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
			request.Method = "DELETE";
			request.ContentType = "application/xml";
			request.Accept = "*/*";

			HttpWebResponse response = (HttpWebResponse)request.GetResponse();
			using (Stream stream = response.GetResponseStream())
			{
				if (stream.CanSeek)
				{
					byte[] data = new byte[stream.Length];
					stream.Read(data, 0, data.Length - 1);
					result = Encoding.UTF8.GetString(data);
				}
			}
		}

		private void lstComments_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			CurrentComment = lstComments.SelectedItem as Comment;
		}

		private void miDeletePerson_Click(object sender, RoutedEventArgs e)
		{
			if (CurrentPerson == null)
			{
				MessageBox.Show("Choose person to delete");
			}

			string url = string.Format(@"http://localhost:2222/RestService/Admin/Person/{0}", CurrentPerson.Id);
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
			request.Method = "DELETE";
			request.Accept = "*/*";
			request.ContentType = "application/xml";

			HttpWebResponse response = request.GetResponse() as HttpWebResponse;
			using (Stream stream = response.GetResponseStream())
			{

			}
		}

		private void btnUpdatePerson_Click(object sender, RoutedEventArgs e)
		{
			if (CurrentPerson == null)
			{
				MessageBox.Show("Choose person to update");
				return;
			}

			Views.AddPersonWindow add = new Views.AddPersonWindow(CurrentPerson);
			if (add.ShowDialog() == true)
			{
				DataContractSerializer ser = new DataContractSerializer(typeof(Person));

				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format(@"http://localhost:22222/RestService/Admin/Person/{0}", CurrentPerson.Id));
				request.Method = "PUT";
				request.Accept = "*/*";
				request.ContentType = "application/xml";
				using (Stream stream = request.GetRequestStream())
				{
					ser.WriteObject(stream, add.PersonInstance);
					stream.Flush();
				}

				HttpWebResponse response = request.GetResponse() as HttpWebResponse;
				using (Stream stream = response.GetResponseStream())
				{
				}
			}
		}

		private void btnUpdateComment_Click(object sender, RoutedEventArgs e)
		{
			if (CurrentComment == null)
			{
				MessageBox.Show("Select comment to update");
				return;
			}

			Views.AddCommentWindow add = new Views.AddCommentWindow(CurrentComment);
			if (add.ShowDialog() == true)
			{
				DataContractSerializer ser = new DataContractSerializer(typeof(Comment));

				string url = string.Format(@"http://localhost:2222/RestService/Admin/Comment/{0}", CurrentComment.CommentId);
				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
				request.Method = "PUT";
				request.Accept = "*/*";
				request.ContentType = "application/xml";
				using (Stream stream = request.GetRequestStream())
				{
					ser.WriteObject(stream, add.CommentData);
					stream.Flush();
				}

				HttpWebResponse response = request.GetResponse() as HttpWebResponse;
				using (Stream stream = response.GetResponseStream())
				{
				}
			}


		}

		private void miJson_Click(object sender, RoutedEventArgs e)
		{
			WindowJsonResponse resp = new WindowJsonResponse();
			resp.Owner = this;

			resp.Show();
		}
	}
}
